#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/9/25 19:22
# @Author : cjw
from sqlalchemy import select, func
from sqlalchemy.orm import Session

from app.models.task import Task
from app.schemas.task import TaskCreate


def get_task_by_id(db: Session, t_id: int):
    """
    根据id查询任务信息
    :param db:
    :param t_id:
    :return:
    """
    return db.get(Task, t_id)


def get_task_count(db: Session):
    """
    获取任务表中的数据总数
    :param db:
    :return: {'count': 0}
    """
    stmt = select(func.count(Task.id).label('count'))
    return db.execute(stmt).mappings().one()


def get_tasks(db: Session, skip: int = 0, limit: int = 10):
    """
    分页获取多个测试任务
    :param db:
    :param skip:
    :param limit:
    :return:
    """
    stmt = select(Task).offset(skip).limit(limit)
    return [task.as_dict() for task in db.execute(stmt).scalars()]


def create_task(db: Session, task: TaskCreate):
    """
    创建任务信息
    :param db:
    :param task:
    :return:
    """
    db_task = Task(**task.dict())
    db.add(db_task)
    db.commit()
    return db_task
